package com.tmt.helper;

import java.util.ArrayList;
import java.util.List;

/**
 * 校验码生成器
 */
public class RandomCodeHelper {

    /**
     * 数字表
     */
    private static final String[] NUMBER_ARRAY = new String[]{"1","2","3","4","5","6","7","8","9","0"};

    /**
     * 字母表
     */
    private static final String[] LETTER_ARRAY = new String[]{
        "A","B","C","D","E","F","G","H","I","J",
        "k","L","M","N","O","P","Q","R","S","T",
        "U","V","W","X","Y","Z"
    };

    /**
     * 得到纯数字串
     * @param len 返回的字符串长度
     * @return
     */
    public static String getNumberCode(int len){
        List<String[]> list = new ArrayList<String[]>(){{
            add(NUMBER_ARRAY);
        }};
        return getCode(list, len);
    }

    /**
     * 得到纯字母串
     * @param len 返回的字符串长度
     * @return
     */
    public static String getLetterCode(int len){
        List<String[]> list = new ArrayList<String[]>(){{
            add(LETTER_ARRAY);
        }};
        return getCode(list, len);
    }

    /**
     * 得到包含数字或字母的随机串
     * @param len 返回的字符串长度
     * @return
     */
    public static String getRandomCode(int len){
        List<String[]> list = new ArrayList<String[]>(){{
            add(NUMBER_ARRAY);
            add(LETTER_ARRAY);
        }};
        return getCode(list, len);
    }

    private static String getCode(List<String[]> optionList, int len){
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < len; i++){
            int d = (int)(1000 * Math.random());
            int unit = 1000 / optionList.size();
            String[] array = optionList.get(d / unit);

            int k = (int)(1000 * Math.random());
            int index = k % array.length;
            sb.append(array[index]);
        }
        return sb.toString();
    }

    public static void main(String[] args){
        System.out.println(RandomCodeHelper.getNumberCode(6));
        System.out.println(RandomCodeHelper.getLetterCode(6));
        System.out.println(RandomCodeHelper.getRandomCode(6));
    }

}
